package beanutils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 对象拷贝
 */
public class BeanUtils {
    /**
     * 两个对象是同一种类型
     *
     * @param srcObject
     * @param targetObject
     */
    public static void copySrcNotNullField(Object srcObject, Object targetObject) {
        // 获取所有字段包括父类
        Field[] subFields = srcObject.getClass().getDeclaredFields();
        Field[] parentFields = srcObject.getClass().getSuperclass().getDeclaredFields();
        Field[] fields = new Field[subFields.length + parentFields.length];
        System.arraycopy(subFields,0,fields,0,subFields.length);
        System.arraycopy(parentFields,0,fields,subFields.length,parentFields.length);
        for (int i = 0; i < fields.length; i++) {
            String fieldName = fields[i].getName();
            fieldName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

            try {
                Method getMethod = srcObject.getClass().getMethod("get" + fieldName);
                Object srcValue = getMethod.invoke(srcObject);
                Object targetValue = getMethod.invoke(targetObject);
                if (srcValue != null && targetValue == null) {
                    String fieldType = fields[i].getGenericType().toString().replaceAll("class ","");
                    System.out.println(fieldType);
                    Method setMethod = srcObject.getClass().getMethod("set" + fieldName, Class.forName(fieldType));
                    setMethod.invoke(targetObject, srcValue);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
